package dao.impl;

import dao.OrderCartDao;
import entity.Order_Cart;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import util.C3P0Util;

import java.sql.SQLException;
import java.util.List;

public class OrderCartDaoImpl implements OrderCartDao{
	//设计方法用于返回操作数据库的qr对象
	private QueryRunner getQueryRunner(){
		return new QueryRunner(C3P0Util.getDataSource());
	}
	
	@Override
	public List<Order_Cart> queryAllOrder_CartListByUserId(Integer user_Id) {
		QueryRunner qr = this.getQueryRunner();
		List<Order_Cart> list = null;
		String sql = "select * from order_cart where user_id = ?";
		try {
			list = qr.query(sql, user_Id,new BeanListHandler<Order_Cart>(Order_Cart.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public int deleteOrderCartByUidAndPid(Integer product_id, Integer model_id ,Integer user_id) {
		QueryRunner qr = this.getQueryRunner();
		String sql = "DELETE FROM order_cart WHERE product_id = ? AND model_id=? AND user_id = ?";
		int i = 0;
		Object[] params = {product_id,model_id,user_id};
		try {
			i = qr.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}

	@Override
	public int countOrderCartDifferentVariety(Integer user_Id) {
		Long i = null;
		QueryRunner qr = this.getQueryRunner();
		String sql = "SELECT COUNT(cart_id) c FROM order_cart WHERE user_id=?";
		try {
			i = (Long)qr.query(sql, user_Id,new ScalarHandler(1));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i.intValue();
	}

	@Override
	public int updateOrderCartByCurrentNeed(Integer product_id, Integer model_id, Integer user_id, Integer need) {
		int i = 0;
		QueryRunner qr = this.getQueryRunner();
		String sql = "update order_cart set product_amount=? where product_id=? and model_id=? and user_id=?";
		Object[] params = {need,product_id,model_id,user_id};
		try {
			i = qr.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}

}
